// 全局变量
let sessionId = localStorage.getItem('sessionId');
let userId = localStorage.getItem('userId');

// 如果没有会话ID，创建一个新的
if (!sessionId) {
    sessionId = generateSessionId();
    localStorage.setItem('sessionId', sessionId);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 检查登录状态
    checkAuthStatus();
    
    // 获取用户ID
    userId = localStorage.getItem('userId');
    
    // 加载历史聊天记录
    loadChatHistory();
    
    // 绑定事件
    document.getElementById('sendButton').addEventListener('click', sendMessage);
    document.getElementById('messageInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
});

// 修改checkAuthStatus函数
async function checkAuthStatus() {
    try {
        const response = await fetch('/api/check-auth');
        const data = await response.json();

        if (!data.authenticated) {
            window.location.href = '/login';
        } else {
            // 从sessionStorage获取用户类型
            const userType = sessionStorage.getItem('user_type');
            // 确保用户在正确的页面
            if ((userType === 'admin' && !window.location.pathname.includes('/admin')) ||
                (userType === 'customer' && !window.location.pathname.includes('/chat'))) {
                window.location.href = userType === 'admin' ? '/admin' : '/chat';
            }
        }
    } catch (error) {
        console.error('检查登录状态失败:', error);
        window.location.href = '/login';
    }
}

// 生成会话ID
function generateSessionId() {
    return 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}

// 发送消息
async function sendMessage() {
    const input = document.getElementById('messageInput');
    const message = input.value.trim();
    
    if (!message) return;
    
    // 添加用户消息到界面
    addMessageToUI('user', message);
    
    // 清空输入框
    input.value = '';

    try {
        const response = await fetch('/api/send_message', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ message: message })
        });

        const data = await response.json();

        if (data.success) {
            addMessageToChat(data.response, 'received');
        } else {
            // 显示具体的错误信息
            addMessageToChat(`抱歉，发送消息失败: ${data.message || '未知错误'}`, 'received');
        }
    } catch (error) {
        console.error('发送消息错误:', error);
        addMessageToChat('网络连接异常，请检查网络后重试', 'received');
    }
}

// 添加消息到界面
function addMessageToUI(role, content, productInfo = null) {
    const chatMessages = document.getElementById('chatMessages');
    const now = new Date();
    const timeString = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message`;
    
    // 产品信息卡片（如果有的话）
    // 修复产品卡片显示
    let productCard = '';
    if (productInfo && productInfo.name) {
        productCard = `
            <div class="product-card">
                <h4>${productInfo.name}</h4>
                <p>价格: ¥${productInfo.price || '未知'}</p>
                ${productInfo.ingredients ? `<p>${productInfo.ingredients}</p>` : ''}
                ${productInfo.effect ? `<p>成分: ${productInfo.effect}</p>` : ''}
                ${productInfo.skin_type ? `<p>适合肤质: ${productInfo.skin_type}</p>` : ''}
            </div>
        `;
    }
    
    messageDiv.innerHTML = `
        <div>${content}</div>
        ${productCard}
        <div class="message-time">今天 ${timeString}</div>
    `;
    
    chatMessages.appendChild(messageDiv);
    
    // 滚动到底部
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 加载聊天历史
async function loadChatHistory() {
    try {
        const response = await fetch(`/api/chat-history?session_id=${sessionId}`);
        const history = await response.json();
        
        if (history && history.length > 0) {
            history.forEach(item => {
                addMessageToUI(
                    item.is_human ? 'user' : 'bot',
                    item.question || item.answer
                );
            });
        } else {
            // 显示欢迎消息
            addMessageToUI('bot', '您好！我是至本电商客服机器人，有什么可以帮您的吗？');
        }
    } catch (error) {
        console.error('加载聊天历史失败:', error);
    }
}

// 添加转接人工客服功能
document.getElementById('transferBtn').addEventListener('click', function(e) {
    e.preventDefault();
    requestHumanService();
});

// 修改requestHumanService函数，确保正确传递userId
async function requestHumanService() {
    try {
        const response = await fetch('/api/request-human-service', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                session_id: sessionId,
                user_id: userId  // 确保正确传递用户ID
            })
        });

        const data = await response.json();
        if (data.success) {
            alert('已请求转接人工客服，请等待管理员接入');
            // 切换到等待视图
            document.querySelector('.menu-item[data-view="transfer"]').click();
        } else {
            alert('请求失败: ' + data.message);
        }
    } catch (error) {
        console.error('转接请求失败:', error);
        alert('转接请求失败，请重试');
    }
}

// 添加检查人工客服连接状态的函数
function checkHumanChatStatus() {
    setInterval(async () => {
        try {
            const response = await fetch(`/api/check-human-chat?user_id=${userId}`);
            const data = await response.json();

            if (data.connected && data.success) {
                // 切换回聊天视图
                document.querySelector('.menu-item[data-view="chat"]').click();
                // 显示管理员已接入信息
                addMessageToUI('bot', '已为您接入人工客服', null);
                // 停止检查
                clearInterval(this);
            }
        } catch (error) {
            console.error('检查人工客服状态失败:', error);
        }
    }, 3000);
}
// 修改loadUserOrders函数，显示售后状态
async function loadUserOrders() {
    try {
        const response = await fetch('/api/get_user_orders');
        const data = await response.json();

        const ordersList = document.getElementById('orders-list');

        if (data.success) {
            if (data.orders.length > 0) {
                ordersList.innerHTML = '';

                data.orders.forEach(order => {
                    const orderCard = document.createElement('div');
                    orderCard.className = 'order-card';

                    // 检查是否有售后申请及状态
                    let afterSalesStatus = '';
                    if (order.after_sales_status === 'pending') {
                        afterSalesStatus = '<div class="after-sales-status pending">售后处理中</div>';
                    } else if (order.after_sales_status === 'rejected') {
                        afterSalesStatus = `
                            <div class="after-sales-status rejected">申请失败</div>
                            <button class="request-after-sales" data-order-id="${order.order_id}">重新申请</button>
                        `;
                    } else if (order.after_sales_status === 'approved') {
                        afterSalesStatus = '<div class="after-sales-status approved">售后已批准</div>';
                    } else {
                        afterSalesStatus = `<button class="request-after-sales" data-order-id="${order.order_id}">申请售后</button>`;
                    }

                    orderCard.innerHTML = `
                        <!-- 订单其他信息 -->
                        ${afterSalesStatus}
                    `;

                    ordersList.appendChild(orderCard);
                });

                // 绑定售后申请按钮事件
                initOrderActions();
            } else {
                ordersList.innerHTML = '<p style="text-align: center; padding: 20px;">暂无订单记录</p>';
            }
        }
    } catch (error) {
        console.error('加载订单错误:', error);
    }
}
// 添加常见问题功能
document.getElementById('faqBtn').addEventListener('click', function(e) {
    e.preventDefault();
    showFAQView();
});

async function showFAQView() {
    document.getElementById('chatMessages').style.display = 'none';
    document.getElementById('afterSalesView').classList.add('hidden');
    document.getElementById('knowledgeView').classList.add('hidden');

    const faqView = document.getElementById('faqView');
    faqView.classList.remove('hidden');

    try {
        const response = await fetch('/api/faq-categories');
        const categories = await response.json();

        const categoriesDiv = document.getElementById('faqCategories');
        categoriesDiv.innerHTML = '';

        categories.forEach(category => {
            const btn = document.createElement('button');
            btn.className = 'btn btn-small';
            btn.textContent = category;
            btn.addEventListener('click', () => loadFAQsByCategory(category));
            categoriesDiv.appendChild(btn);
        });

        if (categories.length > 0) {
            loadFAQsByCategory(categories[0]);
        }
    } catch (error) {
        console.error('加载常见问题失败:', error);
    }
}

async function loadFAQsByCategory(category) {
    try {
        const response = await fetch(`/api/faqs?category=${encodeURIComponent(category)}`);
        const faqs = await response.json();

        const questionsDiv = document.getElementById('faqQuestions');
        questionsDiv.innerHTML = '';

        faqs.forEach(faq => {
            const questionBtn = document.createElement('button');
            questionBtn.className = 'faq-question';
            questionBtn.textContent = faq.question;
            questionBtn.addEventListener('click', () => showFAQAnswer(faq));
            questionsDiv.appendChild(questionBtn);
        });
    } catch (error) {
        console.error('加载问题失败:', error);
    }
}

function showFAQAnswer(faq) {
    const answerDiv = document.getElementById('faqAnswer');
    answerDiv.innerHTML = `<h4>${faq.question}</h4><p>${faq.answer}</p>`;
}

// 添加产品知识库功能
document.getElementById('knowledgeBtn').addEventListener('click', function(e) {
    e.preventDefault();
    showKnowledgeView();
});

async function showKnowledgeView() {
    document.getElementById('chatMessages').style.display = 'none';
    document.getElementById('afterSalesView').classList.add('hidden');
    document.getElementById('faqView').classList.add('hidden');

    const knowledgeView = document.getElementById('knowledgeView');
    knowledgeView.classList.remove('hidden');

    try {
        const response = await fetch('/api/products');
        const products = await response.json();

        const productList = document.getElementById('productList');
        productList.innerHTML = '';

        products.forEach(product => {
            const item = document.createElement('div');
            item.className = 'product-item';
            item.innerHTML = `
                <h4>${product.name}</h4>
                <p>${product.category} | ${product.series}</p>
            `;
            item.addEventListener('click', () => showProductDetails(product.product_id));
            productList.appendChild(item);
        });

        if (products.length > 0) {
            showProductDetails(products[0].product_id);
        }
    } catch (error) {
        console.error('加载产品失败:', error);
    }
}

async function showProductDetails(productId) {
    try {
        const response = await fetch(`/api/product-details/${productId}`);
        const product = await response.json();

        const detailsDiv = document.getElementById('productDetails');
        detailsDiv.innerHTML = `
            <h4>${product.name}</h4>
            <p>类别: ${product.category} | 系列: ${product.series}</p>
            <p>库存: ${product.stock}</p>
            <p>成分: ${product.ingredients || '无'}</p>
            <p>使用方法: ${product.usage_instructions || '无'}</p>
            <p>适合肤质: ${product.skin_type || '无'}</p>
            <p>功效: ${product.effect || '无'}</p>
        `;
    } catch (error) {
        console.error('加载产品详情失败:', error);
    }
}

// 绑定订单按钮
document.getElementById('orderBtn').addEventListener('click', function(e) {
    e.preventDefault();
    showOrderView();
});

// 显示订单视图
function showOrderView() {
    document.getElementById('chatMessages').style.display = 'none';
    document.getElementById('afterSalesView').classList.add('hidden');
    document.getElementById('faqView').classList.add('hidden');
    document.getElementById('knowledgeView').classList.add('hidden');

    const orderView = document.getElementById('orderView');
    orderView.classList.remove('hidden');

    loadUserOrders();
}

// 加载用户订单
async function loadUserOrders() {
    try {
        const response = await fetch('/api/user-orders');
        const orders = await response.json();

        const orderList = document.getElementById('orderList');
        orderList.innerHTML = '';

        if (orders.length === 0) {
            orderList.innerHTML = '<p>您还没有订单记录</p>';
            return;
        }

        orders.forEach(order => {
            const orderItem = document.createElement('div');
            orderItem.className = 'order-item';

            // 根据状态显示时间信息
            let timeInfo = '';
            if (order.status === '已付款') {
                timeInfo = `<p>付款时间: ${order.payment_time || '未记录'}</p>
                            <p>发货时间: 未发货</p>
                            <p>收货时间: 未收货</p>`;
            } else if (order.status === '已发货') {
                timeInfo = `<p>付款时间: ${order.payment_time || '未记录'}</p>
                            <p>发货时间: ${order.shipping_time || '未记录'}</p>
                            <p>收货时间: 未收货</p>`;
            } else {
                timeInfo = `<p>付款时间: ${order.payment_time || '未记录'}</p>
                            <p>发货时间: ${order.shipping_time || '未记录'}</p>
                            <p>收货时间: ${order.delivery_time || '未记录'}</p>`;
            }

            orderItem.innerHTML = `
                <div class="order-header">
                    <span>订单号: ${order.order_id}</span>
                    <span>状态: ${order.status}</span>
                </div>
                <div class="order-body">
                    <p>产品: ${order.product_name}</p>
                    <p>数量: ${order.quantity}</p>
                    <p>总价: ¥${order.total_price}</p>
                    <p>收货地址: ${order.shipping_address}</p>
                    ${timeInfo}
                </div>
            `;
            orderList.appendChild(orderItem);
        });
    } catch (error) {
        console.error('加载订单失败:', error);
        document.getElementById('orderList').innerHTML = '<p>加载订单失败，请重试</p>';
    }
}